package com.xiaobai.sequentialControl;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AlternatingOperation {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1, 5);
        new Thread(()->{waitNotify.print("a",1,2);}).start();
        new Thread(()->{waitNotify.print("b",2,3);}).start();
        new Thread(()->{waitNotify.print("c",3,1);}).start();
    }
}

/*
我要输出的交替的abc
 */
@Slf4j
class WaitNotify {
    public void print(String str, int waitFlag, int nextFlag) {
        for (int i = 0; i < cyclesNumber; i++) {
            synchronized (this){
                while (flag != waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        log.debug("线程被中断了,{}",e.getMessage());
                    }
                }
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }

    //标志位
    private int flag;
    //循环次数
    private int cyclesNumber;

    public WaitNotify(int flag, int cyclesNumber) {
        this.flag = flag;
        this.cyclesNumber = cyclesNumber;
    }
}
